package br.com.post.persistence;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import br.com.post.model.Topic;

public class TopicDao {
	private static TopicDao instance;
	/**
	 * Persiste o topico no banco
	 * @param topic
	 */
	public void createTopic(Topic topic) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		session.save(topic);
		tx.commit();
		session.close();
	}
	
	/**
	 * Atualiza o topico no banco
	 * @param topic
	 */
	public void updateTopic(Topic topic) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		session.merge(topic);
		tx.commit();
		session.close();
	}
	
	/**
	 * Seleciona um topico no banco de acordo com o id(long)
	 * @param topic_id
	 * @return topic
	 */
	public Topic selectTopic(long topic_id) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		Topic topic = (Topic)session.get(Topic.class,topic_id);
		tx.commit();
		session.close();
		return topic;
	}
	
	/**
	 * Deleta o topico de acordo com o id, primeiro faz um select
	 * para o hibernate entender, depois remove o topico selecionado
	 * @param topic_id
	 */
	public void deleteTopic(long topic_id) {
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		Topic topic = selectTopic(topic_id);
		session.delete(topic);
		tx.commit();
		session.close();
	}

	public static TopicDao getInstance() {
		if(instance == null)
			instance = new TopicDao();
		return instance;
	}

	public static void setInstance(TopicDao instance) {
		TopicDao.instance = instance;
	}
	@SuppressWarnings("unchecked")
	public List<Topic> list() {
		
		Session session = HibernateUtil.getSession();
		Transaction tx = session.beginTransaction();
		List<Topic> topicList = session.createQuery("from Topic t order by t.topic_date_create").list();
		
		tx.commit();
		session.close();
		return topicList;
	}
	
}

